package cn.pconline.autoclub.web.usercenter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Level;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.ActivityService;
import cn.pconline.autoclub.service.AlbumService;
import cn.pconline.autoclub.service.ClubLevelService;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.PetrolService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.web.UserAuth;
import cn.pconline.officialclub.entity.OClub;
import cn.pconline.officialclub.service.OClubService;
import cn.pconline.passport2.Account;
import cn.pconline.passport2.Passport;
import cn.pconline.r.client.SimpleHttpTemplate;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;



@Controller
@RequestMapping(value="/usercenter")
public class UserCenterController {
    @Autowired
    private UserAuth userAuth;
    @Autowired
    private ClubService clubService;
    @Autowired
    private OClubService oClubService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private PetrolService petrolService;
    @Autowired
    private ClubLevelService clubLevelService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private AlbumService albumService;
    @Autowired
    private SimpleHttpTemplate simpleHttpTemplate;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private Passport passport;
    @Autowired
    private UserService userService;
    private static final Logger log = LoggerFactory.getLogger(UserCenterController.class);
    /**
     * 是否过滤XSS字符
     */
    private static final int XSSENCODE = 1;
    private static final String XSSENCODE_STRING = "xssEncode";
    /**
     * 接口返回状态码
     */
    private static final int STATUS_NOLOGIN = -2; //未登录
    private static final int STATUS_FAIL = -1; //失败
    private static final int STATUS_OK = 0; // 成功 || 正常
    
    private static final int DEF_PAGESIZE=10;
    private static final int DEF_MAXSIZE = 100;
    private static final int DEF_MINSIZE = 1;
    /**
     * 公用返回JSON数据方法
     * @param resp
     * @param str
     * @param callback 
     */
    private void printJSONMsg(HttpServletResponse resp,String str,String callback){
        try {
            PrintWriter print = resp.getWriter();
            if(StringUtils.isNotBlank(callback)){
                print.println(callback+"("+str+")");
            }else{
                print.println(str);
            }
            print.flush();
            print.close();
        } catch (IOException ex) {
            java.util.logging.Logger.getLogger(UserCenterController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    /**
     * 查询登录用户加入的车友会
     * @param req
     * @param resp 
     */
    @RequestMapping(value="/1.0/club/listMyJoinClub.do",method= RequestMethod.GET)
    public void listMyJoinClub(HttpServletRequest req,HttpServletResponse resp){
        WebUtils.setEncoding(req, resp);
        String callback = WebUtils.param(req, "callback", "");
        int xssEncode = WebUtils.paramInt(req, XSSENCODE_STRING, XSSENCODE);
        User user = userAuth.getUser(req, resp);
        JSONObject obj = new JSONObject();
        if(user!=null && user.getUid()>0){
            List<Club> clubs  = clubService.listByUserId(user.getUid());
            JSONArray array = new JSONArray();
            if(clubs!=null && clubs.size()>0){
                for( Club club : clubs ){
                    array.add(xssEncode==XSSENCODE?club.toJsonEncodeHTML():club.toJson());
                }
            }
            obj.put("data", array);
            obj.put("code", STATUS_OK);
        }else{
            obj.put("code", STATUS_NOLOGIN);
            obj.put("message", "未登录");
        }
          printJSONMsg(resp, obj.toJSONString(), callback);
    }
     /**
     * 查询登录用户加入的车友会(包括品牌车友会)
     * @param req
     * @param resp 
     */
    @RequestMapping(value="/1.0/club/listMyJoinOfficialClub.do",method= RequestMethod.GET)
    public void listMyJoinClubV2(HttpServletRequest req,HttpServletResponse resp){
        WebUtils.setCacheHeader(resp, STATUS_FAIL);
        WebUtils.setEncoding(req, resp);
        String callback = WebUtils.param(req, "callback", "");
        int xssEncode = WebUtils.paramInt(req, XSSENCODE_STRING, XSSENCODE);
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize",DEF_PAGESIZE,DEF_MINSIZE,DEF_MAXSIZE);
        User user = userAuth.getUser(req, resp);
        if(!checkLogin(user)){
            JSONObject json =  new JSONObject();
            json.put("code", -1);
            json.put("message", "用户没有登录");
            printJSONMsg(resp, json.toJSONString(), callback);
            return;
        }
            JSONArray oArray = new JSONArray();
            Pager<OClub> pager = oClubService.pagerClubJoin(user.getUid(),pageNo,pageSize);
            if(pager != null && pager.getResultList()!=null && !pager.getResultList().isEmpty()){
                List<OClub> oClubs = pager.getResultList();
                for(OClub oClub : oClubs){
                    oArray.add(oClub.getJSON(xssEncode==XSSENCODE));
                }
            }
            JSONObject json = pager.toJSONObject(oArray);
            json.put("pageCount", pager.getPageCount());
            json.put("code", STATUS_OK);
          printJSONMsg(resp, json.toJSONString(), callback);
    }
    private boolean checkLogin(User user){
        if(user == null || user.getUid() == 0){
            return false;
        }
        return true;
    }
    /**
     * 个人中心修改绑定手机号码通知接口
     * @param request
     * @param response 
     */
    @RequestMapping(value="/1.0/updateUserBindPhone.do",method= RequestMethod.GET)
    public void updateUserBindPhone(HttpServletRequest request,HttpServletResponse response){
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        User  user = userAuth.getUser(request, response);
        JSONObject obj = new JSONObject();
        if(!checkLogin(user)){
            obj.put("code", -1);
            obj.put("message", "未登录");
             printJSONMsg(response, obj.toJSONString(), callback);
            return;
        }
        Account account = passport.getAccount(user.getUid());
        if(account == null){
            obj.put("code", -1);
            obj.put("message", "找不到用户:"+user.getUid());
            log.error("accountId is not found :"+user.getUid());
            printJSONMsg(response, obj.toJSONString(), callback);
            return;
        }
        if(account.isActivatedMobile()){
            user.setBindPhone(account.getMobile());
        }else{
            user.setBindPhone("");
        }
        user.setIsSyncdPhone(User.IS_SYNC_PHONE);
        userService.updateUser(user);
         obj.put("code", 0);
         obj.put("message", "同步成功");
        printJSONMsg(response, obj.toJSONString(), callback);
    }
}
